<?php
session_start();
require_once 'config/database.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Please login first']);
    exit();
}

if (!isset($_POST['car_id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit();
}

$database = new Database();
$db = $database->getConnection();

$user_id = $_SESSION['user_id'];
$car_id = $_POST['car_id'];

// Check if already in favorites
$check_query = "SELECT id FROM favorites WHERE user_id = ? AND car_id = ?";
$check_stmt = $db->prepare($check_query);
$check_stmt->execute([$user_id, $car_id]);

if ($check_stmt->rowCount() > 0) {
    // Remove from favorites
    $delete_query = "DELETE FROM favorites WHERE user_id = ? AND car_id = ?";
    $delete_stmt = $db->prepare($delete_query);
    
    if ($delete_stmt->execute([$user_id, $car_id])) {
        echo json_encode(['success' => true, 'action' => 'removed']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to remove from favorites']);
    }
} else {
    // Add to favorites
    $insert_query = "INSERT INTO favorites (user_id, car_id) VALUES (?, ?)";
    $insert_stmt = $db->prepare($insert_query);
    
    if ($insert_stmt->execute([$user_id, $car_id])) {
        echo json_encode(['success' => true, 'action' => 'added']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to add to favorites']);
    }
}
?> 